package pages {
	import navigation.Btn;

	import org.splink.deepsplink.authentication.AuthenticatorEvent;
	import org.splink.deepsplink.authentication.IAuthenticator;
	import org.splink.deepsplink.interceptor.IInterceptor;
	import org.splink.deepsplink.page.IAuthenticationPage;
	import org.splink.deepsplink.page.IPageSupplier;
	import org.splink.deepsplink.page.Page;
	import org.splink.library.tween.QTween;
	import org.splink.library.tween.QTweenConst;

	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.events.MouseEvent;

	/**
	 * @author Max Kugland
	 */
	public class LoginPage extends Page implements IAuthenticationPage {

		private var _authenticator : IAuthenticator;
		private var _securityInterceptor : IInterceptor;
		private var _btn : Btn;

		public function LoginPage(supplier : IPageSupplier) {
			super(supplier);
			setup();
		}
		
		private function setup() : void {
			display.x = 150;
			display.y = 30;
			display.alpha = 0;
			
			display.addChild(new Bitmap(new BitmapData(250, 200, false, Math.random() * 1674743789), "auto", true));
		}

		/**
		 * @inheritDoc
		 */
		public function set authenticator(authenticator : IAuthenticator) : void {
			_authenticator = authenticator;
			_authenticator.register(AuthenticatorEvent.LOGIN_SUCCESS, onAuthenticationSuccess);
		}

		/**
		 * @inheritDoc
		 */
		public function set securityInterceptor(securityInterceptor : IInterceptor) : void {
			_securityInterceptor = securityInterceptor;
		}
	
		/**
		 * @inheritDoc
		 */
		override public function initialize() : void {
			setShowStrategy(new QTween(display).duration(300).add(QTweenConst.ALPHA, 1));
			setHideStrategy(new QTween(display).duration(300).add(QTweenConst.ALPHA, 0));
			
			if(!_authenticator.isAuthenticated()) {
				_btn = new Btn("login", "Login");				_btn.addEventListener(MouseEvent.CLICK, onLogin);
			} else {
				_btn = new Btn("logout", "Logout");
				_btn.addEventListener(MouseEvent.CLICK, onLogout);			}
			
			display.addChild(_btn.display).y = 40;
			setInitialized();
		}

		private function onLogout(e : MouseEvent) : void {
			_authenticator.logout();
			navigationCommand.gotoPage("home");
		}

		private function onLogin(e : MouseEvent) : void {
			// no need for an <code>IAuthenticationRequest</code> as <code>TestAuthenticator</code> is only mock			_authenticator.login(null);
		}

		private function onAuthenticationSuccess(e : AuthenticatorEvent) : void {
			navigationCommand.gotoPage(_securityInterceptor.lastInterceptedId);
		}

		/**
		 * @inheritDoc
		 */
		override public function finalize() : void {
			display.removeChild(_btn.display);
		}
	}
}
